<template>
  <!-- 增改用户弹框 -->
  <hcDialog
    dialogWidth="400px"
    :dialogTitle="options.type === 'add' ? '新增设备' : '编辑设备'"
    :isVisable="options.show"
    @closeDialog="closeFun"
    @openDialog="openFun"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-width="6vw"
      status-icon
      :rules="rules"
      :validate-on-rule-change="false"
    >
      <el-form-item prop="factoryCode" label="工厂编号">
        <el-input v-model="form.factoryCode"></el-input>
      </el-form-item>

      <el-form-item prop="deviceCode" label="设备编号">
        <el-input v-model="form.deviceCode"></el-input>
      </el-form-item>

      <el-form-item prop="deviceName" label="设备名称">
        <el-input v-model="form.deviceName"></el-input>
      </el-form-item>
      <el-form-item>
        <div class="btns">
          <el-button type="primary" @click="saveDialog()">保存</el-button>
          <el-button @click="closeFun">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </hcDialog>
</template>

<script setup name="UserDialog">
import { watch, reactive, ref } from "vue";
import { postDevice, putDevice } from "@/api/recipe";
import { getGUID } from "@/utils";

const emit = defineEmits(["closeDialog"]);

const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {
        show: false,
        type: "add", // 用于判断是编辑还是删除 add edit
        data: null, // 当前编辑的用户
      };
    },
  },
});

const formRef = ref();
const form = reactive({
  id: getGUID(),
  factoryCode: "",
  deviceCode: "",
  deviceName: "",
});

const rules = {
  factoryCode: [{ required: true, message: "请输入工厂编号", trigger: "blur" }],
  deviceCode: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  deviceName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
};

function saveDialog() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = "";
      if (props.options.type === "edit") {
        res = await putDevice(form);
      } else {
        res = await postDevice(form);
      }
      if (res) {
        ElMessage.success("保存成功");
        emit("closeDialog", true);
      } else {
        ElMessage.error("保存失败");
      }
    }
  });
}

// 关闭弹框
const closeFun = () => {
  formRef.value?.resetFields();
  emit("closeDialog");
};

function openFun() {
  if (props.options.type === "edit") {
    for (let key in form) {
      form[key] = props.options.data[key];
    }
  }
}
</script>

<style lang="scss" scoped></style>
